import {createStore} from 'vuex'
import {userInfo} from '../apis/login'

export default createStore({
    state: {
        token: '',
        username: '',
        lastIndex: '0',
    },
    getters: {
        isLogin(state) {
            return !!state.token || !!localStorage.getItem('pm_token');
        },
        getIndex(state) {
                // return localStorage.getItem('index');
            return state.lastIndex === '0' ? (!!localStorage.getItem('index') ? localStorage.getItem('index') : '0') : state.lastIndex;
        }
    },
    mutations: {
        setToken(state, token) {
            localStorage.setItem('pm_token', token);
            state.token = token;
        },
        logout(state) {
            localStorage.clear();
            state.token = '';
            state.lastIndex = '0'
        },
        setUsername(state, username) {
            state.username = username;
        },
        changeIndex(state, index) {
            localStorage.setItem('index', index);
            state.lastIndex = index;
        }
    },
    actions: {
        refreshInfo({commit, getters }) {
            if(getters.isLogin) {
                userInfo({}).then((res) => {
                    console.log(res);
                    commit('setUsername', res.data);
                })
            }
        },
        changeIndex({commit}, index) {
            console.log("----"+ index);
            commit('changeIndex', index);
        },
    }
})